package org.robert.export_client.excel.entity;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.robert.export_client.excel.builder.ExcelSheetDataRespBuilder;
import org.robert.export_client.excel.builder.WorkbookDataRespBuilder;
import org.robert.export_client.excel.metadata.AbstractWorkbookWrite;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * WorkbookWrite:
 *
 * @author zhaoshengtao
 * @date 2024/01/22
 */
@Slf4j
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class WorkbookRespWrite extends AbstractWorkbookWrite {

    private WorkbookDataRespBuilder workbookBuilder;

    public WorkbookRespWrite(WorkbookDataRespBuilder workbookBuilder) {
        this.workbookBuilder = workbookBuilder;
    }

    @Override
    public ExcelSheetDataRespBuilder createSheet(String sheetName, Class<?> clazz, Map<String, Map<String, String>> dictMap) throws Exception {

        return this.workbookBuilder.createSheet(sheetName, clazz, dictMap);
    }

    public void finish() {
        OutputStream outputStream = this.workbookBuilder.getOutputStream();
        try {
            this.workbookBuilder.getWorkbook().write(outputStream);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally{
            try {
                outputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
